package com.cll.learn.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * 描述信息:
 *
 * @author CLL
 * @version 1.0
 * @date 2020/10/9 16:36
 */
@WebFilter(filterName = "requestIpFilter", urlPatterns = "/*")
public class WebRequestFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化过滤器。");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            System.out.println("将请求" + request + "放置到threadLocal中。当前线程ID = " + Thread.currentThread().getId());
            WebRequestHolder.settingServletRequest(request);
            chain.doFilter(request, response);
        } finally {
            System.out.println("将请求" + request + "从threadLocal中移除。当前线程ID = " + Thread.currentThread().getId());
            WebRequestHolder.removeServletRequest();
        }
    }

    @Override
    public void destroy() {
        System.out.println("过滤器销毁");
    }
}
